package com.kfm.config;

import com.kfm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

/**
 * Security 配置类
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true, securedEnabled = true) // 开启对于方法注解支持
public class SecurityConfig {

    @Autowired
    private IUserService service;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http.authorizeHttpRequests()  // 认证请求, 进行请求的权限配置
                .antMatchers("/**").hasRole("USER") // 拥有ADMIN角色的用户可以访问所有的URL。hasRole(String)：如果当前用户有String表示的角色，则返回True
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated() // 其他请求要认证通过才能访问（登录）
                .and()
                .formLogin()   // 自定义登录表单
                .loginPage("/login") // 登录页面的请求
                .usernameParameter("username") // 表单用户名的 key
                .passwordParameter("password") // 表单密码的 key
                .loginProcessingUrl("/login")  // 登录校验的请求
                .defaultSuccessUrl("/index")  // 验证成功
                .failureUrl("/error")      // 验证失败请求
                .permitAll()    // 所有人都能访问
                .and()
                .logout()
                .invalidateHttpSession(true) // session 过期
                .logoutUrl("/logout")  // 退出登录请求
                .logoutSuccessUrl("/login") // 退出后跳转的请求
                .permitAll()
                .and()
                .userDetailsService(service)  // 鉴权 userService
                .csrf()
                .disable() // csrf 关闭
                .build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        // 认证管理器
        return authenticationConfiguration.getAuthenticationManager();
    }


}
